package com.micro.user.service.impl;

import com.micro.user.dto.UserInfoDTO;
import com.micro.user.dto.UserProfileDTO;
import com.micro.user.dto.request.LoginRequest;
import com.micro.user.dto.request.RegisterRequest;
import com.micro.user.dto.response.LoginResponse;
import com.micro.user.entity.User;
import com.micro.user.repository.UserRepository;
import com.micro.user.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户服务实现类 - 测试版本
 * 
 * @author micro
 * @since 1.0.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserRepository userRepository;

    @Override
    @Transactional
    public User register(RegisterRequest request) {
        log.info("用户注册开始，用户名：{}", request.getUsername());

        // 验证密码一致性
        if (!request.isPasswordMatch()) {
            throw new IllegalArgumentException("两次输入的密码不一致");
        }

        // 检查用户名是否已存在
        if (!isUsernameAvailable(request.getUsername())) {
            throw new IllegalArgumentException("用户名已存在");
        }

        // 检查身份证号是否已存在
        if (!isIdCardNumberAvailable(request.getIdCardNumber())) {
            throw new IllegalArgumentException("身份证号已被使用");
        }

        // 检查手机号是否已存在
        if (!isPhoneNumberAvailable(request.getPhoneNumber())) {
            throw new IllegalArgumentException("手机号已被使用");
        }

        // 创建用户实体
        User user = new User();
        user.setUsername(request.getUsername());
        user.setPassword(encryptPassword(request.getPassword()));
        user.setRealName(request.getRealName());
        user.setIdCardNumber(request.getIdCardNumber());
        user.setPhoneNumber(request.getPhoneNumber());
        user.setUserType(request.getUserType());
        user.setActive(true);
        user.setRegistrationTime(LocalDateTime.now());
        user.setBalance(BigDecimal.ZERO);
        user.setDeleted(0);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());

        // 保存用户
        userRepository.insert(user);
        log.info("用户注册成功，用户ID：{}", user.getUserId());

        return user;
    }

    @Override
    public LoginResponse login(LoginRequest request) {
        log.info("用户登录开始，用户名：{}", request.getUsername());

        User user = null;

        // 根据登录类型进行不同的登录验证
        if (request.isUsernamePasswordLogin()) {
            user = userRepository.findByUsername(request.getUsername());
            if (user == null || !user.getPassword().equals(encryptPassword(request.getPassword()))) {
                throw new IllegalArgumentException("用户名或密码错误");
            }
        } else if (request.isPhoneVerificationLogin()) {
            // 手机号验证码登录逻辑
            if (!verifyCode(request.getUsername(), request.getVerificationCode())) {
                throw new IllegalArgumentException("验证码错误");
            }
            user = userRepository.findByPhoneNumber(request.getUsername());
        } else if (request.isIdCardLogin()) {
            // 身份证号登录逻辑
            user = userRepository.findByIdCardNumber(request.getUsername());
            if (user == null || !user.getPassword().equals(encryptPassword(request.getPassword()))) {
                throw new IllegalArgumentException("身份证号或密码错误");
            }
        }

        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }

        if (!user.getActive()) {
            throw new IllegalArgumentException("用户已被禁用");
        }

        // 更新最后登录时间
        user.setLastLoginTime(LocalDateTime.now());
        userRepository.updateById(user);

        // 构建登录响应
        LoginResponse response = new LoginResponse();
        response.setUserId(user.getUserId());
        response.setUsername(user.getUsername());
        response.setRealName(user.getRealName());
        response.setUserType(user.getUserType());
        response.setActive(user.getActive());
        response.setBalance(user.getBalance());
        response.setLastLoginTime(user.getLastLoginTime());
        response.setToken(generateToken(user));
        response.setTokenExpireTime(LocalDateTime.now().plusHours(24));

        log.info("用户登录成功，用户ID：{}", user.getUserId());
        return response;
    }

    @Override
    public UserInfoDTO getUserInfo(Long userId) {
        User user = userRepository.selectById(userId);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }
        return convertToUserInfoDTO(user);
    }

    @Override
    public UserInfoDTO getUserInfoByUsername(String username) {
        User user = userRepository.findByUsername(username);
        if (user == null) {
            return null;
        }
        return convertToUserInfoDTO(user);
    }

    @Override
    @Transactional
    public User updateUserProfile(Long userId, UserProfileDTO profileDTO) {
        log.info("更新用户资料，用户ID：{}", userId);
        
        // 暂时返回模拟用户
        User user = new User();
        user.setUserId(userId);
        user.setRealName(profileDTO.getRealName());
        user.setIdCardNumber(profileDTO.getIdCardNumber());
        user.setPhoneNumber(profileDTO.getPhoneNumber());
        user.setUserType(profileDTO.getUserType());
        user.setActive(profileDTO.getActive());
        user.setUpdateTime(LocalDateTime.now());
        
        return user;
    }

    @Override
    @Transactional
    public boolean changePassword(Long userId, String oldPassword, String newPassword) {
        log.info("修改密码，用户ID：{}", userId);
        return true;
    }

    @Override
    @Transactional
    public boolean resetPassword(String username, String idCardNumber, String newPassword) {
        log.info("重置密码，用户名：{}", username);
        return true;
    }

    @Override
    @Transactional
    public boolean recharge(Long userId, BigDecimal amount) {
        log.info("用户充值，用户ID：{}，充值金额：{}", userId, amount);
        
        try {
            User user = userRepository.selectById(userId);
            if (user == null) {
                log.error("用户不存在，用户ID：{}", userId);
                return false;
            }
            
            user.recharge(amount);
            userRepository.updateById(user);
            log.info("用户充值成功，用户ID：{}，新余额：{}", userId, user.getBalance());
            return true;
        } catch (Exception e) {
            log.error("用户充值失败，用户ID：{}，错误：{}", userId, e.getMessage());
            return false;
        }
    }

    @Override
    @Transactional
    public boolean consume(Long userId, BigDecimal amount) {
        log.info("用户消费，用户ID：{}，消费金额：{}", userId, amount);
        
        try {
            User user = userRepository.selectById(userId);
            if (user == null) {
                log.error("用户不存在，用户ID：{}", userId);
                return false;
            }
            
            boolean success = user.consume(amount);
            if (success) {
                userRepository.updateById(user);
                log.info("用户消费成功，用户ID：{}，新余额：{}", userId, user.getBalance());
                return true;
            } else {
                log.error("用户余额不足，用户ID：{}，当前余额：{}，消费金额：{}", userId, user.getBalance(), amount);
                return false;
            }
        } catch (Exception e) {
            log.error("用户消费失败，用户ID：{}，错误：{}", userId, e.getMessage());
            return false;
        }
    }

    @Override
    public BigDecimal getUserBalance(Long userId) {
        try {
            User user = userRepository.selectById(userId);
            if (user == null) {
                log.error("用户不存在，用户ID：{}", userId);
                return BigDecimal.ZERO;
            }
            return user.getBalance();
        } catch (Exception e) {
            log.error("获取用户余额失败，用户ID：{}，错误：{}", userId, e.getMessage());
            return BigDecimal.ZERO;
        }
    }

    @Override
    public List<UserInfoDTO> getUsersByType(Integer userType) {
        return new ArrayList<>();
    }

    @Override
    public List<UserInfoDTO> getAllActiveUsers() {
        return new ArrayList<>();
    }

    @Override
    @Transactional
    public boolean disableUser(Long userId) {
        log.info("禁用用户，用户ID：{}", userId);
        return true;
    }

    @Override
    @Transactional
    public boolean enableUser(Long userId) {
        log.info("启用用户，用户ID：{}", userId);
        return true;
    }

    @Override
    @Transactional
    public boolean deleteUser(Long userId) {
        log.info("删除用户，用户ID：{}", userId);
        return true;
    }

    @Override
    public Long countUsers() {
        return 1L;
    }

    @Override
    public Long countUsersByType(Integer userType) {
        return 1L;
    }

    @Override
    public boolean isUsernameAvailable(String username) {
        try {
            User existingUser = userRepository.findByUsername(username);
            return existingUser == null;
        } catch (Exception e) {
            log.error("检查用户名可用性失败，用户名：{}，错误：{}", username, e.getMessage());
            return false;
        }
    }

    @Override
    public boolean isIdCardNumberAvailable(String idCardNumber) {
        try {
            User existingUser = userRepository.findByIdCardNumber(idCardNumber);
            return existingUser == null;
        } catch (Exception e) {
            log.error("检查身份证号可用性失败，身份证号：{}，错误：{}", idCardNumber, e.getMessage());
            return false;
        }
    }

    @Override
    public boolean isPhoneNumberAvailable(String phoneNumber) {
        try {
            User existingUser = userRepository.findByPhoneNumber(phoneNumber);
            return existingUser == null;
        } catch (Exception e) {
            log.error("检查手机号可用性失败，手机号：{}，错误：{}", phoneNumber, e.getMessage());
            return false;
        }
    }

    @Override
    public boolean sendVerificationCode(String phoneNumber) {
        log.info("发送验证码到手机号：{}", phoneNumber);
        return true;
    }

    @Override
    public boolean verifyCode(String phoneNumber, String code) {
        log.info("验证手机号：{}，验证码：{}", phoneNumber, code);
        return "123456".equals(code);
    }

    /**
     * 加密密码
     */
    private String encryptPassword(String password) {
        return DigestUtils.md5DigestAsHex(password.getBytes());
    }

    /**
     * 生成登录令牌
     */
    private String generateToken(User user) {
        return "token_" + user.getUserId() + "_" + System.currentTimeMillis();
    }

    /**
     * 转换为UserInfoDTO
     */
    private UserInfoDTO convertToUserInfoDTO(User user) {
        UserInfoDTO dto = new UserInfoDTO();
        BeanUtils.copyProperties(user, dto);
        // TODO: 设置乘客数量
        dto.setPassengerCount(0);
        return dto;
    }
}
